<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['sa:plan:query']">
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" size="small" clearable filterable placeholder="请选择省份" style="width: 100%;">
          <el-option
            v-for="item in provinceList"
            :key="item.code"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年份" prop="name">
        <!--        <el-input v-model.trim="queryParams.name" :maxlength="15" size="small" placeholder="请输入名称"></el-input>-->
        <el-date-picker
          type="year"
          v-model="queryParams.name"
          placeholder="选择销售计划年份"
          value-format="yyyy"
          size="small"
        />
      </el-form-item>
      <el-form-item label="销售经理" prop="saleManager">
        <el-input v-model.trim="queryParams.saleManager" clearable :maxlength="15" size="small"
                  placeholder="请输入销售经理名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:plan:add']"
                     @click="openDialog(null)">增加
          </el-button>
          <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:activity:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      highlight-current-row
      max-height="680"
      v-loading="loading"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="province"
        align="center"
        label="省份"
        width="100"
      />
      <el-table-column
        prop="saleManager"
        align="center"
        label="销售经理"
        width="100"
      />
      <el-table-column
        property="name"
        label="名称"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.name + '年销售计划' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="totalSale"
        align="center"
        label="年度目标(万元)"
      />
      <el-table-column
        prop="q1Sale"
        align="center"
        label="第一季度金额(万元)"
      />
      <el-table-column
        prop="q2Sale"
        align="center"
        label="第二季度金额(万元)"
      />
      <el-table-column
        prop="q3Sale"
        align="center"
        label="第三季度金额(万元)"
      />
      <el-table-column
        prop="q4Sale"
        align="center"
        label="第四季度金额(万元)"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="80"
      />
      <!-- <el-table-column
        property="updateBy"
        label="修改人"
        align="center"
        width="80"
      /> -->
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('sa:plan:view') || $auth.hasPermi('sa:plan:edit') || $auth.hasPermi('sa:plan:remove')"
      >
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" v-hasPermi="['sa:plan:view']" @click="viewHandler(scope.row, 1)">
            查看详细
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" v-hasPermi="['sa:plan:editDetail']" @click="viewHandler(scope.row, 2)">
            修改详细
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" v-hasPermi="['sa:plan:edit']" @click="openDialog(scope.row)">
            修改
          </el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" size="mini" icon="el-icon-delete" type="text" v-hasPermi="['sa:plan:remove']" style="margin-left: 10px"
            >删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '增加' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" clearable filterable placeholder="请选择省份" style="width: 100%;">
            <el-option
              v-for="item in provinceList"
              :key="item.code"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售经理" prop="saleManager">
          <el-select v-model="form.saleManager" allow-create clearable filterable placeholder="请选择销售经理" style="width: 100%;">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userName">
                </el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="财年" prop="name">
          <el-date-picker
            v-model="form.name"
            type="year"
            value-format="yyyy"
            placeholder="选择财年"
            style="width: 100%;"
          />
          <!-- <el-input v-model.trim="form.name" :maxlength="4" placeholder="请填写财年"/> -->
        </el-form-item>
        <el-form-item label="年度目标" prop="totalSale">
          <el-input
            v-model.trim="form.totalSale"
            type="number"
            :min="0"
            disabled
            placeholder="年度目标"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="第一季度" prop="q1Sale">
          <el-input
            v-model.trim="form.q1Sale"
            type="number"
            :min="0"
            placeholder="请输入第一季度金额"
            @input="inputHandler1"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="第二季度" prop="q2Sale">
          <el-input
            v-model.trim="form.q2Sale"
            type="number"
            :min="0"
            placeholder="请输入第二季度金额"
            @input="inputHandler2"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="第三季度" prop="q3Sale">
          <el-input
            v-model.trim="form.q3Sale"
            type="number"
            :min="0"
            placeholder="请输入第三季度金额"
            @input="inputHandler3"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="第四季度" prop="q4Sale">
          <el-input
            v-model.trim="form.q4Sale"
            type="number"
            :min="0"
            placeholder="请输入第四季度金额"
            @input="inputHandler4"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">继续</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/plan";
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import PlanDetail from "@/views/crm/sa/plan/detail.vue";
import { listUser } from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: 'PlanView',
  components: {PlanDetail},
  dicts: ['sys_activity_type'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      projectDate: [],
      // 加载动画
      loading: true,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 活动日期
      activityDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        saleManager: "", // 销售经理
        name: "",
        province: "", // 省份
        activityDate: "", // 活动日期 *
        content: "", // 活动内容 *
        createBy: "", // 创建人 *
        createTime: "", // 创建时间 *
        endDate: "", // 活动结束时间
        q1Sale: "", // 第一季度金额
        q2Sale: "", // 第二季度金额
        q3Sale: "", // 第三季度金额
        q4Sale: "", // 第四季度金额
        totalSale: "", //
        id: null, // id
        remark: "", // 备注
        startDate: "", // 活动开始时间
        type: 1, // 类型 * 0 服务大赛、展会等活动
        updateBy: "", // 更新时间
        updateTime: "", // 更新人
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        content: [
          {required: true, message: '请填写活动内容', trigger: 'blur'}
        ],
        saleManager: [
          {required: true, message: '请选择销售经理', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请填写财年', trigger: 'change'}
        ],
        province: [
          {required: true, message: '请选择省份', trigger: 'change'}
        ],
        activityDate: [
          {required: true, message: '请选择日期', trigger: 'change'}
        ],
        q1Sale: [
          {required: true, message: '请填写第一季度金额', trigger: 'blur'}
        ],
        q2Sale: [
          {required: true, message: '请填写第二季度金额', trigger: 'blur'}
        ],
        q3Sale: [
          {required: true, message: '请填写第三季度金额', trigger: 'blur'}
        ],
        q4Sale: [
          {required: true, message: '请填写第四季度金额', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        saleManager: "", // 销售经理名称
        name: "",
        province: "",
        createBy: "", // 创建人 *
        endDate: "", // 活动结束时间
        startDate: "", // 活动开始时间
        type: null, // 类型 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      userList: [],
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getUserList()
  },
  activated() {
    this.getList()
    this.getUserinfo()
  },
  methods: {
    async getUserList() {
      listUser({
        pageSize: 500,
      }).then(response => {
          this.userList = (response.rows ?? []).filter(i => !i.admin)
        }
      );
    },
    // 用户输入的回调
    inputHandler1(e, index) {
      if (+e < 0) this.form.q1Sale = 0

      const {
        q1Sale,
        q2Sale,
        q3Sale,
        q4Sale,
      } = this.form

      this.form.totalSale = +(q1Sale || 0) + +(q2Sale || 0) + +(q3Sale || 0) + +(q4Sale || 0)
    },
    inputHandler2(e, index) {
      if (+e < 0) this.form.q2Sale = 0
      const {
        q1Sale,
        q2Sale,
        q3Sale,
        q4Sale,
      } = this.form

      this.form.totalSale = +(q1Sale || 0) + +(q2Sale || 0) + +(q3Sale || 0) + +(q4Sale || 0)
    },
    inputHandler3(e, index) {
      if (+e < 0) this.form.q3Sale = 0
      const {
        q1Sale,
        q2Sale,
        q3Sale,
        q4Sale,
      } = this.form

      this.form.totalSale = +(q1Sale || 0) + +(q2Sale || 0) + +(q3Sale || 0) + +(q4Sale || 0)
    },
    inputHandler4(e, index) {
      if (+e < 0) this.form.q4Sale = 0
      const {
        q1Sale,
        q2Sale,
        q3Sale,
        q4Sale,
      } = this.form

      this.form.totalSale = +(q1Sale || 0) + +(q2Sale || 0) + +(q3Sale || 0) + +(q4Sale || 0)
    },
    // 展示销售计划word的回调
    viewHandler(row, type) {
      // 1是查看 2是修改
      this.$router.push({name: 'PlanDetail', query: {plan: row.id, type, name: row.name}})
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      // 1是查看 2是修改 3是新增
      // if(row) {
      //   this.$router.push({ name: 'PlanDetail', query: { plan: row.id, type: 2, name: row.name }})
      // } else {
      //   this.$router.push({ name: 'PlanDetail', query: { type: 3 }})
      // }
      if (row) {
        this.formId = row.id
        this.form = { ...row }
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/plan/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `plans_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        name: this.form.name,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.viewHandler({id: res.data}, 2)
        this.formId = -1
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        name: this.form.name,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss">

</style>
